package com.hz.friends.fragment;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.hz.friends.customView.CustomToast;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Toast;

public abstract class BaseFragment extends Fragment {

	protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected String TAG = this.getClass().getSimpleName();

	protected abstract void init();

	protected abstract void initViews();

	protected abstract void setViews();

	protected abstract void initEvents();
	
	public abstract void initDatas();

	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.execute());
	}
	

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}
	public void showToast(String text) {
		CustomToast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
	}

	public void showSysToast(String text) {
		if(getActivity() == null)
			return;
		Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
	}

	/** ͨ��Class��ת���� **/
	protected void startActivity(Class<?> cls) {
		startActivity(cls, null);
	}

	/** ����Bundleͨ��Class��ת���� **/
	protected void startActivity(Class<?> cls, Bundle bundle) {
		Intent intent = new Intent();
		intent.setClass(getActivity(), cls);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivity(intent);
	}

	/** ͨ��Action��ת���� **/
	protected void startActivity(String action) {
		startActivity(action, null);
	}

	/** ����Bundleͨ��Action��ת���� **/
	protected void startActivity(String action, Bundle bundle) {
		Intent intent = new Intent();
		intent.setAction(action);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivity(intent);
	}

	public View findViewById(int id) {
		return getView().findViewById(id);
	}

	// @Override
	// protected void onDestroy() {
	// clearAsyncTask();
	// super.onDestroy();
	// }
	@Override
	public void onDestroy() {
		super.onDestroy();
		clearAsyncTask();
		super.onDestroy();
	}
}
